import Singleton from "./Singleton";
import MsgHints from "../framwork/MsgHints";
import Utils from '../utils/Utils';
import Http from "../utils/HTTP";
const wx = window["wx"]

const { ccclass, property } = cc._decorator;
export default class AdCenter extends Singleton {
    VideoAd = null;
    gridAdLft = null;
    gridAdRight = null;
    gridAdJz = null;
    bannerAd = null;


    customTopId: string = ''
    customTopAd = null

    customLeftOneAd = null
    GridLeftId_1: string = ''

    customRightOneAd = null
    GridRightId_1: string = ''
    

    _windowHeight = 0;
    _windowWidth = 0;
    showGridJzTime = 0;
    _adtop = 100;

    BANNER_ID:string=''
    VIDEO_ID:string=''
    interstitialAd = null
    CHAPIN_ID:string=''
    GRIDLEFT_ID:string=''
    GRIDRIGHT_ID:string=''
    GRIDJZ_ID:string=''

    offon:boolean = false

    getWxIdFromServer(callback,fail) {
        if(!wx){
            fail&&fail()
            return
        }
        try{

            let appid = wx.getAccountInfoSync().miniProgram.appId
            Http.sendRequest('', {appid:appid,version:'1.5'}, (result) => {
                if(result.data.other.ad_lv){
                    localStorage.setItem("ad_lv",result.data.other.ad_lv)
                }
                this.offon = result.data.offon?result.data.offon:false
                result.data = result.data.ads
                let sysInfo = wx.getSystemInfoSync()
                this._windowWidth = sysInfo.windowWidth
                this._windowHeight = sysInfo.windowHeight
                

                if(this._windowHeight>900){
                    this.GRIDLEFT_ID = result.data.GridLeftId_5
                    this.GRIDRIGHT_ID = result.data.GridRightId_5
                }else if(this._windowHeight>800){
                    this.GRIDLEFT_ID = result.data.GridLeftId_4
                    this.GRIDRIGHT_ID = result.data.GridRightId_4
                }else{
                    this.GRIDLEFT_ID = result.data.GridLeftId_3
                    this.GRIDRIGHT_ID = result.data.GridRightId_3
                }

                this.GRIDJZ_ID = result.data.GridJzId
                this.BANNER_ID = result.data.bannerId
                this.VIDEO_ID = result.data.videoAdId
                this.CHAPIN_ID = result.data.interstitialId
                this.customTopId = result.data.GridTopId_5

                this.GridLeftId_1 = result.data.gameCustomLeftId
                this.GridRightId_1 = result.data.gameCustomRightId

                console.log(result.data)
                callback && callback()
                console.log('banner,video,inters', this.BANNER_ID, this.VIDEO_ID, this.CHAPIN_ID)
            }, 'https://box.jiezhui.top/wxapp/xcxgame/getGameConfig.html', () => {
                fail&&fail()
                console.log('请求错误')
            })

        }catch{
            fail&&fail()
        }
    }


    public getAdLevl(){
        let ad_lv = []
        if(localStorage.getItem("ad_lv")){
            console.log('https_lv',localStorage.getItem("ad_lv"))
            return localStorage.getItem("ad_lv")
        }else{
            ad_lv = [
                5,10,15,20,25
            ]
            return ad_lv
        }
    }


    public getOffOn() {
        return this.offon
    };

    init() {
      
        if (cc.sys.platform == cc.sys.WECHAT_GAME && wx.createRewardedVideoAd) {
            this.VideoAd = wx.createRewardedVideoAd({
                adUnitId: this.VIDEO_ID
            });

            this.VideoAd.onError((res) => {
                console.log("onError", res);
                MsgHints.show("广告加载错误");
            });

            this.VideoAd.onLoad(() => {
                // console.log('广告加载成功');
            })

            this.VideoAd.onClose(res => {
                if (res && res.isEnded || res === undefined) {
                    cc.log("正常播放结束，可以下发游戏奖励")
                    this.callBack(true);
                }
                else {
                    cc.log("播放中途退出，不下发游戏奖励")
                    this.callBack(false);
                }
            })

            // 创建插屏广告实例，提前初始化
            if (wx.createInterstitialAd) {
                this.interstitialAd = wx.createInterstitialAd({
                    adUnitId: this.CHAPIN_ID
                })

                this.interstitialAd.onError((res) => {
                    console.log("插屏onError", res);
                });
            }

            // 创建格子广告实例，提前初始化
           
        }
    }


    private createInterstitialAd(){
        console.log('创建插屏广告')
        this.interstitialAd = wx.createInterstitialAd({
            adUnitId: this.CHAPIN_ID,
        })
        this.interstitialAd.onError(err => {
            console.log("插屏onError");
            return
        });
        this.interstitialAd.onLoad(() => {
            this.showinterstitialAd()
        })
    }


    public showinterstitialAd() {
        console.log('显示插屏广告')
        // 在适合的场景显示插屏广告
        if (!this.interstitialAd) {
            this.createInterstitialAd()
        }

        this.interstitialAd.show().catch((err) => {
            this.showGridAdJz()
            console.log(err);
        })
    }

    private createGridAdJz(){

        this.gridAdJz = wx.createCustomAd({
            adUnitId: this.GRIDJZ_ID,
            style: {
                left: 0,
                top:100,
                width: this._windowWidth,
                fixed: true
            }
        })
        this.gridAdJz.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.gridAdJz.onLoad(() => {
            this.showGridAdJz()
        })
    }


     //格子广告矩阵
     public showGridAdJz(): void {
        if (!wx) return
        console.log("显示格子广告矩阵")
        if((Math.floor(new Date().getTime() / 1000))-this.showGridJzTime<10){
            console.log("显示格子广告矩阵时间太短")
            return
        }

        if (!this.gridAdJz) {
            this.createGridAdJz()
            return
        }
        this.gridAdJz.show().catch((err)=>{
            this.createGridAdJz()
        })
        
       this.showGridJzTime =  Math.floor(new Date().getTime() / 1000);
    }

    public hideGrudAdJz() {
        if (this.gridAdJz) {
            this.gridAdJz.hide().catch((err) => {
                console.log('隐藏满屏格子广告失败', err);
            })
        }
    }


    private createGridLeftOne(){
        this.customLeftOneAd = wx.createCustomAd({
            adUnitId: this.GridLeftId_1,
            style: {
                left: 60,
                top: this._windowHeight-170,
                width: 100,
                fixed: true
            }
        })
        this.customLeftOneAd.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.customLeftOneAd.onLoad(() => {
            this.showGridAdLeftOne()
        })
    }

    public showGridAdLeftOne(): void {
        console.log('showGridAdLeftOne')
        if (!wx) return
        if (!this.customLeftOneAd) {
            this.createGridLeftOne()
            return
        }
        this.customLeftOneAd.show().catch((err)=>{
            this.createGridLeftOne()
        })
    }

    public hideGridAdLeftOne() {
        if (this.customLeftOneAd) {
            this.customLeftOneAd.hide().catch((err) => {
            })
        }
    }


    private createGridRightOne(){
        console.log('createGridRightOne',this.GridRightId_1)
        this.customRightOneAd = wx.createCustomAd({
            adUnitId: this.GridRightId_1,
            style: {
                left: this._windowWidth-120,
                top: this._windowHeight-170,
                width: 100,
                fixed: true
            }
        })
        this.customRightOneAd.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.customRightOneAd.onLoad(() => {
            this.showGridAdRightOne()
        })
    }

    public showGridAdRightOne(): void {
        if (!wx) return
        if (!this.customRightOneAd) {
            this.createGridRightOne()
            return
        }
        this.customRightOneAd.show().catch((err)=>{
            this.createGridRightOne()
        })
    }

    public hideGridAdRightOne() {
        if (this.customRightOneAd) {
            this.customRightOneAd.hide().catch((err) => {
            })
        }
    }

    private createGridAdLeft(){
        this.gridAdLft = wx.createCustomAd({
            adUnitId: this.GRIDLEFT_ID,
            style: {
                left: 10,
                top:this._adtop,
                fixed: true
            }
        })
        this.gridAdLft.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.gridAdLft.onLoad(() => {
            this.showGridAdLeft()
        })
    }


     //格子广告矩阵
     public showGridAdLeft(): void {
        if (!wx) return
        console.log("显示左边格子广告")

        if (!this.gridAdLft) {
            this.createGridAdLeft()
            return
        }
        this.gridAdLft.show().catch((err)=>{
            this.createGridAdLeft()
        })
        
    }

    public hideGrudAdLeft() {
        if (this.gridAdLft) {
            this.gridAdLft.hide().catch((err) => {
                console.log('隐藏左边格子广告失败', err);
            })
        }
    }


    private createGridAdRight(){
        this.gridAdRight = wx.createCustomAd({
            adUnitId: this.GRIDRIGHT_ID,
            style: {
                left: this._windowWidth-70,
                top: this._adtop,
                fixed: true
            }
        })
        this.gridAdRight.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.gridAdRight.onLoad(() => {
            this.showGridAdRight()
        })
    }


     //格子广告矩阵
     public showGridAdRight(): void {
        if (!wx) return
        console.log("显示左边格子广告")

        if (!this.gridAdRight) {
            this.createGridAdRight()
            return
        }
        this.gridAdRight.show().catch((err)=>{
            this.createGridAdRight()
        })
        
    }

    public hideGrudAdRight() {
        if (this.gridAdRight) {
            this.gridAdRight.hide().catch((err) => {
                console.log('隐藏左边格子广告失败', err);
            })
        }
    }



    private createGridAdTop(){
        console.log('创建顶部格子广告：',this.customTopId)
        this.customTopAd = wx.createCustomAd({
            adUnitId: this.customTopId,
            style: {
                left: (this._windowWidth-290)/2,
                top:0,
                width: 0,
                fixed: true
            }
        })
        this.customTopAd.onError(err => {
            console.log('顶部格子广告加载失败：',err.errMsg)
            return
        });
        this.customTopAd.onLoad(() => {
            console.log('顶部格子广告加载成功')
            this.showGridAdTop()
        })
    }


     //格子广告矩阵
     public showGridAdTop(): void {
        if (!wx) return
            console.log("显示顶部格子广告")

        if (!this.customTopAd) {
            this.createGridAdTop()
            return
        }
        this.customTopAd.show().catch((err)=>{
            this.createGridAdTop()
        })
        
    }

    public hideGridAdTop() {
        if (!wx) return
        if (this.customTopAd) {
            this.customTopAd.hide().catch((err) => {
                console.log('隐藏左边格子广告失败', err);
            })
        }
    }




    public showBanner(): void {
        if (!this.bannerAd) {
            this.createBanner(this.BANNER_ID);
        }
        this.bannerAd.show();
    }

    public createBanner(bannerId: string) {

        // 创建一个居于屏幕底部正中的广告
        this.bannerAd = wx.createBannerAd({
            adUnitId: bannerId,
            adIntervals: 60,
            style: {
                width: this._windowWidth>350?350:this._windowWidth,
                left: this._windowWidth>350?(this._windowWidth-350)/2:0,
                top: 0
            }
        });


        if (!this.bannerAd) {
            return
        }

        this.bannerAd.onLoad(() => {
            this.showBanner()
        })

        //如果不需要让banner在底部，则注释掉onResize回调即可
        this.bannerAd.onResize(res => {
            this.bannerAd.style.top = this._windowHeight - this.bannerAd.style.realHeight;
        })

        this.bannerAd.onError((e) => {
            console.log('banner广告出错：'+e)
        })
    }

    
    public hideBanner(): void {
        if (!this.bannerAd) return;
        this.bannerAd.hide();
    }


    private callBack: Function;
    private _lasttryplaytime: number = 0;

    //type 暂时没有用
    public play(type: number, callback: Function) {
        if (Utils.getServerTime() - this._lasttryplaytime < 1000) {
            console.log("点击过于频繁")
            return;
        }
        console.log("尝试播放广告")
        this._lasttryplaytime = Utils.getServerTime();
        this.callBack = callback;

        if (cc.sys.platform == cc.sys.WECHAT_GAME && this.VideoAd) {
            // 用户触发广告后，显示激励视频广告
            this.VideoAd.show().catch(() => {
                // 失败重试
                this.VideoAd.load()
                    .then(() => this.VideoAd.show())
                    .catch(err => {
                        cc.log('激励视频 广告显示失败');
                        // MsgHints.show("暂时没有广告" + err.errCode + "/" + err.errMsg);
                        this.callBack(false);
                    })
            })
        }
        else {
            this.callBack(true);
        }
    }
}